package org.example.servicemanage.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.example.model.manage.bean.Result;
import org.example.model.manage.bean.po.security.User;
import org.example.servicemanage.client.WXFeignClient;
import org.example.servicemanage.config.YmlConfig;
import org.example.servicemanage.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Tag(name = "用户管理", description = "用户登录、注册、登出等接口")
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private WXFeignClient wxFeignClient;

    @Operation(summary = "刷新微信Token", description = "刷新微信Token")
    @GetMapping("/flash")
    public Result flash(){
        try {
            YmlConfig.WX_TOKEN = wxFeignClient.getToken(YmlConfig.WX_GRANT_TYPE, YmlConfig.WX_APPID, YmlConfig.WX_SECRET).getAccess_token();
        } catch (Exception e) {
            return Result.error(50001, "获取微信Token失败" + e.getMessage());
        }
        return Result.success(null);
    }

    @Operation(summary = "用户登录", description = "用户通过账号密码登录系统")
    @PostMapping("/login")
    public Result login(
            @Parameter(description = "用户账号") @RequestParam String account,
            @Parameter(description = "用户密码") @RequestParam String password) {
        if(account == null || password == null)  return Result.error(10006, "参数错误");

        String JWT = userService.login(account, password);

        return Result.success(JWT);
    }

    @Operation(summary = "用户登出", description = "用户退出登录")
    @PostMapping("/logout")
    public Result logout(HttpServletRequest request){
        userService.logout(request.getHeader("Authorization"));
        return Result.success(null);
    }

    @Operation(summary = "获取用户信息", description = "获取当前登录用户的详细信息")
    @GetMapping("/info")
    public Result info(){
        return Result.success(userService.getUserInfo());
    }

    @Operation(summary = "用户注册", description = "新用户注册账号")
    @PostMapping("/register")
    public Result register(
            @Parameter(description = "用户账号") @RequestParam String account,
            @Parameter(description = "用户密码") @RequestParam String password){
        if(account == null || password == null || account.isEmpty() || password.isEmpty())  return Result.error(10006, "账号或密码为空");
        User user = new User();
        user.setAccount(account);
        user.setPassword(password);
        userService.createUser(user);
        return Result.success(null);
    }

}
